import {
  computed,
  h,
  onMounted,
  reactive,
  ref,
  type Ref,
  shallowRef,
  watch
} from "vue";
import { useDataSyncStore } from "@/store/modules/dataSync";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { ElMessage, ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { UserItem } from "./type/userTypes";
import userForm from "../componentsForm/userForm.vue";
// 添加userBindForm组件导入
import userBindForm from "../components/userBindForm.vue";
import loginBindForm from "../components/loginBindForm.vue";
import { setOriginalFormId, setOriginalFormName } from "./rule/userRules";
import { hideTextAtIndex } from "@pureadmin/utils";
import { usePublicHooks } from "@/views/system/hooks";
import { type as _type } from "os";
import { handleTree } from "@/utils/tree";

export function useUserTable(
  tableRef: Ref,
  lesseeId: number,
  tenantName: string,
  dealerId: number
) {
  const form = reactive({
    username: "",
    phone: "",
    email: "",
    status: "",
    SearchTerm: "",
    OrderBy: ""
  });
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const formRef = shallowRef();
  const dataList = ref<UserItem[]>([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  // 添加分类列表响应式变量
  const categorizeOptions = ref<{ label: string; value: number }[]>([]);
  const zoneOptions = ref<{ label: string; value: number }[]>([]);
  // 添加设备列表响应式变量
  const deviceOptions = ref<{ label: string; value: number }[]>([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 添加获取分类列表函数
  function getCategorizeList() {
    const params = {
      tenantId: lesseeId
    };

    http
      .get(changeHttpLink(`/api/UserCategorize/tenant/${lesseeId}`), { params })
      .then((res: any) => {
        if (res.Success) {
          // 格式化分类数据为下拉列表所需格式
          categorizeOptions.value = res.Data.map((item: any) => ({
            label: item.Name,
            value: item.Id
          }));
          // 添加默认选项
          categorizeOptions.value.unshift({
            label: "无分类",
            value: 0
          });
          console.log("分类列表数据:", categorizeOptions.value); // 添加调试信息
        } else {
          ElMessage.error(res.Message);
        }
      })
      .catch(err => {
        ElMessage.error(err.message);
      });
  }

  //添加获取分区列表函数
  function getZoneList() {
    http
      .get(changeHttpLink("/api/Zone/select"), {
        params: {
          tenantId: lesseeId
        }
      })
      .then((res: any) => {
        if (res.Success) {
          // 转换为树形结构
          zoneOptions.value = handleTree(
            res.Data || [],
            "Id",
            "ParentZoneId",
            "children"
          );
          console.log("分区列表数据:", zoneOptions.value);
        } else {
          ElMessage.error(res.Message);
        }
      })
      .catch(err => {
        ElMessage.error(err.message);
      });
  }
  //添加获取设备列表函数
  function getDeviceList() {
    const params = {
      page: 1,
      pageSize: 100, // 获取所有设备
      tenantId: lesseeId
      //dealerId: useUserStoreHook()?.userId ?? 0
    };

    http
      .get(changeHttpLink("/api/Device"), { params })
      .then((res: any) => {
        if (res.Success) {
          console.log("设备列表数据:", res.Data.Items);

          // 格式化设备数据为下拉列表所需格式
          deviceOptions.value = res.Data.Items.map((item: any) => ({
            label: item.Name, // 假设设备名称字段为Name
            value: item.Id // 假设设备ID字段为Id
          }));
          // 添加默认选项
          deviceOptions.value.unshift({
            label: "无设备",
            value: 0
          });
          console.log("设备列表数据:", deviceOptions.value);
        } else {
          ElMessage.error(res.Message);
        }
      })
      .catch(err => {
        ElMessage.error(err.message);
      });
  }

  // 列表列定义
  const columns = [
    {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    },
    {
      label: "用户号",
      prop: "No",
      width: 80
    },
    {
      label: "用户名",
      prop: "Name",
      minWidth: 100
    },

    /* {
      label: "经销商名称",
      prop: "DealerName",
      width: 150
    },
    {
      label: "租户名称",
      prop: "TenantName",
      width: 150
    }, */
    {
      label: "区域名称",
      prop: "ZoneName",
      width: 150
    },

    {
      label: "用户类型",
      prop: "TypeTxt",
      minWidth: 80
    },
    {
      label: "是否遥毙",
      prop: "_Bi",
      width: 80,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row._Bi}
          active-value={true}
          inactive-value={false}
          active-text="是"
          inactive-text="否"
          inline-prompt
          style={switchStyle.value}
          onChange={() => handleChangeOne(scope as any)}
        />
      )
    },
    {
      label: "是否遥晕",
      prop: "_Yun",
      width: 80,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row._Yun}
          active-value={true}
          inactive-value={false}
          active-text="是"
          inactive-text="否"
          inline-prompt
          style={switchStyle.value}
          onChange={() => handleChangeTwo(scope as any)}
        />
      )
    },
    {
      label: "用户状态",
      prop: "Disabled",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.Disabled}
          active-value={true}
          inactive-value={false}
          active-text="已失效"
          inactive-text="未失效"
          inline-prompt
          style={switchStyle.value}
          onChange={() => handleChangeThird(scope as any)}
        />
      )
    },
    {
      label: "权限等级",
      prop: "Power",
      minWidth: 80,
      formatter: row => "等级 " + row.Power
    },
    {
      label: "默认频道",
      prop: "DefChannelName",
      minWidth: 100
    },
    {
      label: "默认联系人",
      prop: "DefContactName",
      minWidth: 100
    },
    {
      label: "用户分类",
      prop: "CategorizeName",
      minWidth: 80
    },
    {
      label: "关联设备ID",
      prop: "RefDeviceName",
      minWidth: 100
    },

    {
      label: "电话",
      prop: "Tel",
      minWidth: 140,
      formatter: ({ Tel }) => hideTextAtIndex(Tel, { start: 3, end: 6 })
    },

    {
      label: "GPS间隔",
      prop: "Gps",
      width: 120,
      formatter: row => row.Gps + "秒"
    },
    {
      label: "过期时间",
      prop: "Expire",
      width: 180,
      formatter: row => {
        if (row.Expire) {
          return row.Expire.replace("T", "/").replace(/\.\d{3}Z?$/, "");
        }
        return row.Expire;
      }
    },
    {
      label: "视频账号",
      prop: "VideoID",
      width: 150
    },

    {
      label: "备注说明",
      prop: "Comment",
      width: 150
    },
    {
      label: "创建时间",
      prop: "CreateTime",
      width: 180,
      formatter: row => {
        if (row.CreateTime) {
          return row.CreateTime.replace("T", "/").replace(/\.\d{3}Z?$/, "");
        }
        return row.CreateTime;
      }
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "h-[20px]!",
      "reset-margin",
      "text-gray-500!",
      "dark:text-white!",
      "dark:hover:text-primary!"
    ];
  });

  // 获取、搜索用户列表
  function onSearch() {
    loading.value = true;
    const params = {
      PageIndex: pagination.currentPage,
      PageSize: pagination.pageSize,
      SearchTerm: form.SearchTerm,
      tenantId: lesseeId
    };
    console.log(params);
    http
      .get(changeHttpLink("/api/User"), {
        params
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          const listData = res.Data.Items || [];
          const listCheckKey = [
            "CategorizeName",
            "DefChannelName",
            "DefContactName",
            "RefDeviceName"
          ];
          const checkKey2Text = {
            CategorizeName: "未分类",
            DefChannelName: "未配置",
            DefContactName: "",
            RefDeviceName: "未关联"
          };
          for (const item of listData) {
            item._Bi = !(item.Bi == 0);
            item._Yun = !(item.Yun == 0);
            switch (item.Type) {
              case 1:
                item.TypeTxt = "普通对讲用户";
                break;
              case 2:
                item.TypeTxt = "调度台用户";
                break;
            }
            Object.keys(item).forEach(key => {
              if (listCheckKey.includes(key)) {
                if (item[key] == null) {
                  item[key] = checkKey2Text[key];
                }
              }
            });
          }
          dataList.value = listData;
          pagination.total = res.Data.TotalCount || 0;
          console.log(dataList.value);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  function handleChangeOne({ row, index }) {
    onChange(row, index, 1);
  }

  function handleChangeTwo({ row, index }) {
    onChange(row, index, 2);
  }

  function handleChangeThird({ row, index }) {
    onChange(row, index, 3);
  }

  function onChange(row, index, type) {
    let objKey = "";
    let apiUrl = "";
    let tips = "";
    switch (type) {
      case 1: //遥毙
        apiUrl = `/api/User/${row.Id}/toggle-bi`;
        objKey = "_Bi";
        tips = !row._Bi ? "取消遥毙状态" : "设置为遥毙状态";
        break;
      case 2: //遥晕
        apiUrl = `/api/User/${row.Id}/toggle-yun`;
        objKey = "_Yun";
        tips = !row._Yun ? "取消遥晕状态" : "设置为遥晕状态";
        break;
      case 3: //用户状态
        apiUrl = `/api/User/${row.Id}/toggle-status`;
        objKey = "Disabled";
        tips = !row.Disabled ? "设置为未失效" : "设置为已失效";
        break;
    }
    ElMessageBox.confirm(
      `确认要<strong>${
        tips
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.Name
      }</strong>用户吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        http
          .post(changeHttpLink(apiUrl), {
            data: {
              id: row.Id
            }
          })
          .then((res: any) => {
            if (res.Success) {
              message("操作成功", {
                type: "success"
              });
              onSearch();
            } else {
              !row[objKey] ? (row[objKey] = true) : (row[objKey] = false);
              message(res.Message, { type: "error" });
            }
            switchLoadMap.value[index] = Object.assign(
              {},
              switchLoadMap.value[index],
              {
                loading: false
              }
            );
            loading.value = false;
          })
          .catch(err => {
            !row[objKey] ? (row[objKey] = true) : (row[objKey] = false);
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        !row[objKey] ? (row[objKey] = true) : (row[objKey] = false);
      });
  }

  // 新增、修改用户
  function openDialog(title: string, Type: number, row: any = null) {
    console.log(Type);
    getCategorizeList();
    getZoneList();
    getDeviceList();
    const id = row?.Id ?? 0;
    const originalName = row?.username ?? "";
    const originalId = row?.Id ?? 0;
    setOriginalFormName(originalName);
    setOriginalFormId(originalId); // 设置原始用户ID
    addDialog({
      title: `${title}${Type === 2 ? "调度员" : "用户"}`,
      props: {
        formInline: {
          id: row?.Id ?? 0,
          no: row?.No ?? 0,
          dealerId: dealerId,
          tenantId: lesseeId,
          zoneId: row?.ZoneId ?? 0,
          name: row?.Name ?? "",
          type: row?.Type ?? Type,
          power: row?.Power ?? 0,
          defChannel: row?.DefChannel ?? 0,
          defContact: row?.DefContact ?? 0,
          categorizeId: row?.CategorizeId ?? 0,
          refDeviceId: row?.RefDeviceId ?? 0,
          disabled: row?.disabled ?? false,
          tel: row?.Tel ?? "",
          bi: row?.Bi ?? 0,
          yun: row?.Yun ?? 0,
          gps: row?.Gps ?? 0,
          expire: row?.Expire ?? "",
          videoId: row?.VideoID ?? "",
          comment: row?.Comment ?? ""
        },
        title: title,
        originalName: originalName,
        originalId: originalId,
        categorizeOptions: categorizeOptions.value,
        zoneOptions: zoneOptions.value
      },
      width: "640px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(userForm, {
          ref: formRef,
          formInline: null,
          title: title,
          originalName: originalName,
          originalId: originalId,
          categorizeOptions: categorizeOptions.value,
          zoneOptions: zoneOptions.value,
          onRefreshData: () => {
            console.log(
              "[UserTable] Received refresh-data event, updating zone list..."
            );
            getZoneList();
          }
        }),

      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = formRef.value.getFormData();
        curData.tenantId = lesseeId;

        function chores() {
          message(`您${title}了用户ID为【${curData.name}】的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据

          // 通知全局用户数据更新
          const dataSyncStore = useDataSyncStore();
          dataSyncStore.notifyUserDataUpdated();
        }

        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            const formData = {
              ...curData,
              tenantId: lesseeId
            };
            console.log(formData);
            if (title === "创建") {
              http
                .post(changeHttpLink("/api/User"), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            } else {
              http
                .request("put", changeHttpLink(`/api/User/${id}`), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            }
          }
        });
      }
    });
  }

  // 删除用户
  function handleDelete(row: UserItem) {
    ElMessageBox.confirm(
      `是否确认删除用户ID为${row.Id}的这条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        loading.value = true;
        http
          .request("delete", changeHttpLink(`/api/User/${row.Id}`), {
            data: row.Id
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`您删除了用户ID为${row.Id}的这条数据`, {
                type: "success"
              });
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 批量删除
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const listIds = curSelected.map(item => item.Id);

    ElMessageBox.confirm(
      `是否确认删除选中的${listIds.length}条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        loading.value = true;
        http
          .post(changeHttpLink("/api/User/batch-delete"), {
            data: { ids: listIds }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`已删除选中的${listIds.length}条数据`, {
                type: "success"
              });
              tableRef.value.getTableRef().clearSelection();
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 分页大小变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    onSearch();
  }

  // 处理当前页变化
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  // 多选框变化
  function handleSelectionChange(val: UserItem[]) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }

  // 多选框反选
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  // 重置表单
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    form.username = "";
    onSearch();
  }

  // 设备检测
  function deviceDetection() {
    return window.innerWidth <= 1024;
  }
  function handleUpdate(row) {
    console.log(row);
  }

  // 绑定
  function handleBind(row: UserItem, title: string) {
    console.log(title);
    console.log("用户数据", row);
    // 创建对话框并嵌入绑定组件
    addDialog({
      title: title,
      width: "500px",
      draggable: true,
      // 隐藏底部按钮
      hideFooter: true,
      // 传递props给组件
      props: {
        row: row,
        title: title,
        categorizeOptions: categorizeOptions.value,
        zoneOptions: zoneOptions.value,
        deviceOptions: deviceOptions.value
      },
      // 使用组件作为内容
      contentRenderer: () =>
        h(userBindForm, {
          row: row,
          title: title,
          categorizeOptions: categorizeOptions.value,
          zoneOptions: zoneOptions.value,
          deviceOptions: deviceOptions.value
        })
    });
  }
  //登录绑定函数
  function handleLoginBind(row: UserItem) {
    console.log("登录绑定用户数据", row);
    // 创建对话框并嵌入登录绑定组件
    addDialog({
      title: "登录绑定 - " + row.Name,
      width: "800px",
      style: {
        height: "600px"
      },
      draggable: true,
      // 隐藏底部按钮
      hideFooter: true,
      // 传递props给组件
      props: {
        row: row
      },
      // 使用组件作为内容
      contentRenderer: () =>
        h(loginBindForm, {
          row: row
        })
    });
  }
  onMounted(() => {
    // 初始化加载数据
    onSearch();
    // 初始化获取分类列表
    getCategorizeList();
    getZoneList();
    getDeviceList();

    // 监听全局数据更新
    const dataSyncStore = useDataSyncStore();
    watch(
      () => dataSyncStore.zoneDataTimestamp,
      () => {
        console.log(
          "[UserTable] Detected zone data update, refreshing zone list..."
        );
        getZoneList();
      }
    );

    // 监听分类数据更新
    watch(
      () => dataSyncStore.categorizeDataTimestamp,
      () => {
        console.log(
          "[UserTable] Detected categorize data update, refreshing categorize list..."
        );
        getCategorizeList();
      }
    );
  });

  return {
    form,
    formRef,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleDelete,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange,
    categorizeOptions,
    zoneOptions,
    deviceOptions,
    handleBind,
    handleLoginBind,
    handleUpdate
  };
}
